package com.zp.security.oauth2.exception;

import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;

/**
 * ClientCredentialsTokenEndpointFilter这个过滤器作为客户端和密钥的门户过滤器类似于UsernamePasswordAuthenticationFilter
 * 当出现密钥和客户端不对时我们可以，在处理失败逻辑时返回相应的错误,类似于上篇中的LoginAuthenticationFailureHandler
 *
 * @author zp
 */
@RequiredArgsConstructor
public class MyClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {

    private final AuthorizationServerSecurityConfigurer configurer;
    private final OAuthServerAuthenticationFailureHandler oAuthServerAuthenticationFailureHandler;


    /**
     * 构造方法
     * @param configurer AuthorizationServerSecurityConfigurer 对象
     */

    /**
     * 需要重写这个方法，返回AuthenticationManager
     */
    @Override
    protected AuthenticationManager getAuthenticationManager() {
        return configurer.and().getSharedObject(AuthenticationManager.class);
    }

    /**
     * 设置AuthenticationEntryPoint主要逻辑
     */
    @Override
    public void afterPropertiesSet() {
        //自定义认证失败处理器
        setAuthenticationFailureHandler(oAuthServerAuthenticationFailureHandler);
        //成功处理器，和父类相同，为空即可。
        setAuthenticationSuccessHandler((request, response, authentication) -> {
        });
    }
}
